﻿using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using RxxApi.Common.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RxxApi.Extensions.ServiceExtensions;

public static class CorsSetup
{
    public static void AddCorsSetup(this IServiceCollection services, Action<CorsOptions>? setupAction = null)
    {
        if (services == null) throw new ArgumentNullException(nameof(services));

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(policy =>
            {
                if (AppSettings.AllowCors.Any(c => c == "*"))
                {
                    // 允许任意跨域
                    policy.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                }
                else
                {
                    // 允许指定域名
                    policy.WithOrigins(AppSettings.AllowCors)
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                }
            });
        });

        // 自定义配置
        if (setupAction != null)
        {
            services.Configure<CorsOptions>(setupAction);
        }
    }
}
